package br.com.gecandango.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import br.com.gecandango.beans.Cardapio;
import br.com.gecandango.beans.Cardapio_Refeicao;
import br.com.gecandango.beans.Refeicao;
import br.com.gecandango.service.CardapioService;
import br.com.gecandango.service.RefeicaoService;

public class CardapioServiceImpl extends HibernateDaoSupport implements
	CardapioService {
	
	public Cardapio save(Cardapio bean) {
		Long id;
		if(bean.getId()==null){
			id =  (Long)getHibernateTemplate().save(bean);
			bean.setId(id);
		} else {
			getHibernateTemplate().saveOrUpdate(bean);
		}
		return bean;
	}
	public List<Cardapio> list() {
		return getHibernateTemplate().find("from Cardapio");
	}
	public Cardapio find(Long id) {
		List<Cardapio> e = (List<Cardapio>)getHibernateTemplate().find("from Cardapio where id=?", id);
		Cardapio cardapio = e.get(0);
		List<Cardapio_Refeicao> cr = (List<Cardapio_Refeicao>)getHibernateTemplate().find("from Cardapio_Refeicao where id_cardapio="+id+"");
		List<Refeicao> refeicoes = new ArrayList<Refeicao>();
		for (Cardapio_Refeicao cardapio_Refeicao : cr) {
			refeicoes.add(findRefeicao(cardapio_Refeicao.getRefeicao().getId()));
		}
		cardapio.setRefeicoes(refeicoes);
		
		return cardapio;
	}
	
	public void delete(Cardapio bean) {
		getHibernateTemplate().delete(bean);
	}
	
	public Refeicao save(Refeicao bean) {
		Long id;
		if(bean.getId()==null){
			id =  (Long)getHibernateTemplate().save(bean);
			bean.setId(id);
		} else {
			getHibernateTemplate().saveOrUpdate(bean);
		}
		return bean;
	}
	public List<Refeicao> listRefeicoes() {
		return getHibernateTemplate().find("from Refeicao");
	}
	public Refeicao findRefeicao(Long id) {
		List<Refeicao> e = (List<Refeicao>)getHibernateTemplate().find("from Refeicao where id=?", id);
		return e.get(0);
	}
	
	public void delete(Refeicao bean) {
		getHibernateTemplate().delete(bean);
	}
	
}
